<?php

define('IMAGE_TARGET',Mage::getBaseDir('media').'/catalog/product/'); //windows

class ProductImagesImport extends ImportBase 
{
	protected $db;
	
	private $product_table = 'products';
	
	protected $data = array ();
	protected $fp;
	
	protected $attrCodes = array ('thumbnail','small_image','image'  );
	
	function __construct() {
		global $config;
		//echo "{$config['db_host']},{$config['db_user']},{$config['db_pass']},{$config['db_name']}";
		$this->set_s_db( $config['db_host'],$config['db_user'],$config['db_pass'],$config['db_name'] );
		parent::__construct();
		
		$this->db = Mage::getSingleton ( 'core/resource' )->getConnection ( 'core_write' );
		/*
		for($i = 1; $i < 4; $i ++) {
			if ($resRow ['image' . $i]) {
				if (file_exists ( IMAGE_SOURCE . $resRow ['image' . $i] )) {
					echo "{$resRow ['image' . $i]}is_exit->";
					$file_original = $resRow ['image' . $i];
					//$file = substr ( $resRow ['image' . $i], 1 );
					$folder = IMAGE_TARGET . substr ( $file_original, 1, 1 ) . DS . substr ( $file_original, 2, 1 );
					//image_path use web path,don't use the physical path
					$resRow ['image_path' . $i] = '/' . substr ( $file_original, 1, 1 ) . '/' . substr ( $file_original, 2, 1 ) . '/' . $file_original;
					$this->data = $resRow;
					$this->fp = $fp;
					
					if (! is_dir ( $folder )) {
						mkdir ( $folder, 0775, true );
						chmod ( $folder, 0775 );
					}
					//echo "file{$i}{$resRow ['image' . $i]}=" . $file;
					copy ( IMAGE_SOURCE . $file_original, $folder . DS . $file_original );
					chmod ( $folder . DS . $file_original, 0775 );
					chgrp ( $folder . DS . $file_original, 'apache' );
				//echo "target=".$folder . DS . $file_original;
				}
			}
		}
		*/
	}
	
	function run()
	{
		$products_to_import = $this->getAllProduct();
		if( count( $products_to_import ) ){
			foreach( $products_to_import as $product_image ){
				$row_data = $product_image;
				$images_counter = 1;
				foreach( $product_image as $field => $value ){
					if( $field == 'products_image' || $field == 'products_image_med' || $field == 'products_image_lrg' ){
						unset( $row_data[ $field ] );
						$field = 'image_'.$images_counter++;
						//$row_data[ $field ] = str_replace( 'upload/images_upload/','',$value );
						$row_data[ $field ] = 'images/'.$value;
					}
				}
				
				$this->import_product_images( $row_data );
			}
		}
		
	}
	
	function import_product_images( $resRow )
	{
		$images_import = array();
		for($i = 1; $i < 4; $i ++) {
			
			if ($resRow ['image_' . $i]) {
					
				if (file_exists ( BASE_IMPORT_DIR .'/'. $resRow ['image_' . $i] ) && is_file( BASE_IMPORT_DIR .'/'. $resRow ['image_' . $i] ) ) {
					
					$file_original = basename( $resRow ['image_' . $i] );
					
					//$file = substr ( $resRow ['image' . $i], 1 );
					$folder = IMAGE_TARGET . substr ( $file_original, 0, 1 ) . DS . substr ( $file_original, 1, 1 );
					//image_path use web path,don't use the physical path
					$resRow ['image_path' . $i] = '/' . substr ( $file_original, 0, 1 ) . '/' . substr ( $file_original, 1, 1 ) . '/' . $file_original;
					
					
					if (! is_dir ( $folder )) {
						echo $folder;
						spip_make_dir ( $folder,0775 );
					}
					//echo "file{$i}{$resRow ['image' . $i]}=" . $file;
					copy ( BASE_IMPORT_DIR .'/'. $resRow ['image_' . $i], $folder . DS . $file_original );
					chmod ( $folder . DS . $file_original, 0775 );
					chgrp ( $folder . DS . $file_original, 'apache' );
					$images_import[] = $resRow ['image_' . $i];
				//echo "target=".$folder . DS . $file_original;
				}
			}
		}
		echo 'Now try to import product:'.$resRow['product_id'].'<br />';
		$this->data = $resRow;
		$this->setCatalogProductEntityVarchar ( $resRow['product_id'] );
		$this->s_db->query( "update `{$this->log_table}` set images_import = '".count( $images_import )."' where product_id = '{$resRow['product_id']}' and product_id is not null" );
		$this->transation_commit();
	}
	
	protected function getAllProduct()
	{
		$query = "select lt.product_id,p.products_image,p.products_image_med,p.products_image_lrg from `{$this->product_table}` p join `{$this->log_table}` lt on p.products_id = lt.org_product_id where lt.images_import is null";
		
		$this->s_db->query( $query );
		echo $this->s_db->num_rows() .' totals need to import<br />';
		return $this->s_db->af();
	}
	
	function importAction() {
		if (isset ( $this->data ['sku'] )) {
			$entity_id = $this->db->fetchOne ( "select entity_id from catalog_product_entity where sku = '{$this->data['sku']}'" );
			if ($entity_id) {
				$this->setCatalogProductEntityVarchar ( $entity_id );
			}
		}
	}
	
	function setCatalogProductEntityVarchar( $entity_id) {
		$attribute_media_gallery = $this->_getEavAttribute ( 'media_gallery' );
		$entity_type_id = $this->_getEntityType ();
		for($i = 1; $i < 4; $i ++) { //import image1,image2,image3
			if (isset ( $this->data ['image_path' . $i] )) { //only image1 setted as small_image,thumb_image,image
				$attrCode = $this->attrCodes[$i-1];
				//image small_image	thumbnail
				$attribute_id = $this->_getEavAttribute ( $attrCode );
				if ($this->data ['image_path' . $i]) {
					$value_id_xxx = $this->db->fetchOne ( "select value_id from catalog_product_entity_varchar where `entity_type_id` = '{$entity_type_id}' and `attribute_id` = '{$attribute_id}' and `entity_id` = '{$entity_id}'" );
					if ($value_id_xxx) {
						$this->db->query ( "UPDATE `catalog_product_entity_varchar` SET `value` = '{$this->data['image_path'.$i]}' WHERE `entity_id` = '{$entity_id}' and `attribute_id` = '{$attribute_id}' and `entity_type_id` = '{$entity_type_id}'" );
					} else {
						$this->db->query ( "insert into catalog_product_entity_varchar (entity_type_id,attribute_id,store_id,entity_id,value) values ('{$entity_type_id}','{$attribute_id}','0','{$entity_id}','{$this->data['image_path'.$i]}')" );
					}
				}
				
			}
			if (isset ( $this->data ['image_path' . $i] )) {
				$value_id = $this->db->fetchOne ( "select value_id from catalog_product_entity_media_gallery where `value` = '{$this->data['image_path'.$i]}' and `entity_id` = '{$entity_id}' and `attribute_id` = '{$attribute_media_gallery}'" );
				if ($value_id)
					$this->db->query ( "UPDATE `catalog_product_entity_media_gallery_value` SET `label` = '', `position` = '{$i}' WHERE `value_id` = '{$value_id}'" );
				else {
					$this->db->query ( "insert into catalog_product_entity_media_gallery (attribute_id,entity_id,value) values ('{$attribute_media_gallery}','{$entity_id}','{$this->data['image_path'.$i]}')" );
					$lastInsertId = $this->db->lastInsertId ();
					$this->db->query ( "insert into catalog_product_entity_media_gallery_value (value_id,store_id,label,position,disabled) values ('{$lastInsertId}','0','','{$i}','0')" );
				}
			}
		
		}
		
	}
	
	protected function _getEntityType( $entityTypeCode = 'catalog_product') {
		return Mage::getModel ( 'eav/entity_type' )->loadByCode ( $entityTypeCode )->getEntityTypeId ();
	}
	
	protected function _getEavAttribute( $attributeCode,  $entityTypeCode = 'catalog_product') {
		$entityTypeId = $this->_getEntityType ( $entityTypeCode );
		return $this->db->fetchOne ( 'SELECT `attribute_id` FROM eav_attribute where `entity_type_id` = "' . $entityTypeId . '" and `attribute_code` = "' . $attributeCode . '"' );
	}
	
	protected function _getEavAttributeSet( $entityTypeCode = 'catalog_product',  $attributeSetName = 'Default') {
		$entityTypeId = $this->_getEntityType ( $entityTypeCode );
		return $this->db->fetchOne ( 'SELECT `attribute_set_id` FROM eav_attribute_set where `entity_type_id` = "' . $entityTypeId . '" and `attribute_set_name` = "' . $attributeSetName . '"' );
	}

}